﻿module Lhz.Page {
    export class Page {
        private rootWindowIndex: Index;
        private indexOptions: Lhz.Interface.Page.IndexOptions;
        user: Lhz.Entity.ServiceCenter.User;
        indexInitialized: boolean = false;

        constructor(options: Lhz.Interface.Page.IndexOptions = null) {
            this.indexOptions = $.extend({
                checkLogin: true,
                checkRole: true
            }, options);
            if (this.indexOptions.checkLogin) {
                this.user = JSON.parse(this.getSessionStorage("user"));
                if (!this.user) {
                    alert("请先登录。");
                    window.location.href = "/view/login.html";
                    return;
                }
            }
            if (this.indexOptions.checkRole) {
                var admin = $("html").attr("admin");
                if (admin !== undefined) {
                    if (!this.user.IsAdmin) {
                        alert("此页面只有管理员可以查看，请联系管理员分配权限。");
                        return;
                    }
                }
            }
            this.indexInitialized = true;
            $("body").addClass("ui-widget ui-widget-content");
            $("input").addClass("ui-corner-all");
            $("select").addClass("ui-corner-all");
            var rootWindow: Window = window;
            while (rootWindow.parent && rootWindow.parent.location.href != rootWindow.location.href) {
                rootWindow = rootWindow.parent;
            }
            this.rootWindowIndex = rootWindow["index"];

            var skin = this.getLocalStorage("skin");
            if (!skin) {
                skin = "redmond";
                this.setLocalStorage("skin", skin);
                this.refreshSkin(skin);
            }
            this.registerSkinListener();
        }

        getUrlParameter(key: string): string {
            var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) {
                return r[2];
            }
            return null;
        }

        getLocalStorage(key: string): string {
            return window.localStorage.getItem(key);
        }

        setLocalStorage(key: string, value: string) {
            window.localStorage.setItem(key, value);
        }

        getSessionStorage(key: string): string {
            return window.sessionStorage.getItem(key);
        }

        setSessionStorage(key: string, value: string) {
            window.sessionStorage.setItem(key, value);
        }

        private registerSkinListener() {
            var page = this;
            window.addEventListener("storage", function (e) {
                if (e.key == "skin") {
                    page.refreshSkin(e.newValue);
                }
            });
        }

        private refreshSkin(skin: string) {
            var skinStart = "/css/jquery/jquery-ui/";
            var skinEnd = "/jquery-ui.css";
            $("link").each(function () {
                var reg = new RegExp("^.+" + skinStart + ".+" + skinEnd + "$");
                if (reg.test(this.href)) {
                    this.href = skinStart + skin + skinEnd;
                }
            });
        }

        getValue(selector: string): any|any[] {
            var values: any[] = [];
            for (var control of <HTMLElement[]>$(selector).toArray()) {
                if (control instanceof HTMLInputElement && control.type == "checkbox") {
                    values.push(control.checked);
                }
                else if (control instanceof HTMLSpanElement) {
                    values.push(control.innerText);
                }
                else {
                    values.push($(control).val());
                }
            }
            if (values.length == 0) {
                return null;
            }
            else if (values.length == 1) {
                return values[0];
            }
            return values;
        }

        setValue(selector: string, value: any|any[]) {
            $.each($(selector), function (controlIndex: number, control: HTMLElement) {
                if (control instanceof HTMLInputElement && control.type == "checkbox") {
                    control.checked = value;
                }
                else if (control instanceof HTMLSpanElement) {
                    control.innerText = value;
                }
                else {
                    $(control).val(value);
                }
            });
        }

        bindSelect<T>(selector: string, data: T[], idPath: string = null, textPath: string = null) {
            $(selector).each(function (controlIndex: number, control: HTMLSelectElement) {
                $(control).empty();
                var optionPleaseSelect = new Option("请选择", "");
                control.add(optionPleaseSelect);
                for (var item of data) {
                    var optionItem = new Option(textPath ? item[textPath] : item.toString(), idPath ? item[idPath] : undefined);
                    control.add(optionItem);
                }
            });
        }

        showDialog(options: Lhz.Interface.Dialog.DialogOptions): any {
            var currentFolder = location.href;
            currentFolder = currentFolder.substring(0, currentFolder.lastIndexOf("/") + 1);
            options.url = currentFolder + options.url;
            this.rootWindowIndex.indexShowDialog(options);
        }

        getDialogArguments(): any {
            return this.rootWindowIndex.indexGetDialogArguments(this.getUrlParameter("dialogIndex"));
        }

        closeDialog(returnValue: any = null, serialize: boolean = false) {
            if (serialize) {
                returnValue = JSON.stringify(new Json.CycleJson().decycle(returnValue));
            }
            this.rootWindowIndex.indexCloseDialog(this.getUrlParameter("dialogIndex"), returnValue, serialize);
        }

        showLoading() {
            this.rootWindowIndex.showLoading();
        }

        closeLoading() {
            this.rootWindowIndex.closeLoading();
        }

        destroyIframe(iframe: any) {
            iframe.src = 'about:blank';
            try {
                if (iframe.window) {
                    if (iframe.window.contentWindow) {
                        this.destroyIframe(iframe.window.contentWindow);
                    }
                    iframe.window.document.write('');
                    iframe.window.document.clear();
                    iframe.window.close();
                }
                if (iframe.contentWindow) {
                    if (iframe.contentWindow.contentWindow) {
                        this.destroyIframe(iframe.contentWindow.contentWindow);
                    }
                    iframe.contentWindow.document.write('');
                    iframe.contentWindow.document.clear();
                    iframe.contentWindow.close();
                }
                $(iframe).remove();
            } catch (e) {
                alert(e);
            }
        }

        refreshIframe(iframe: any) {
            if (iframe.window) {
                iframe.window.location.reload();
            }
            if (iframe.contentWindow) {
                iframe.contentWindow.location.reload();
            }
        }
    }
}
